/*
 * Copyright (C) 2008 nextcode:ch
 * 
 * Author: Michele Dell'Ambrogio, m@nextcode.ch
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as 
 * published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */
package sfplayer.grabber;

import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import sfplayer.datatypes.Broadcast;
import sfplayer.init.Preferences;

/**
 *
 * @author micc
 */
public class BroadcastsBuilder {

    List<Broadcast> broadcasts = null;

    public BroadcastsBuilder() {
        
        HttpGrabber httpGrabber = new HttpGrabber();
        httpGrabber.openConnection(Preferences.getUrlGrabber());
        String xmlString = httpGrabber.getHttpString();
        
        XmlParser xmlParser = new XmlParser();
        Document doc = xmlParser.process(xmlString);
        
        createBroadcasts(doc); 
    }

    private void createBroadcasts(Document doc) {

        broadcasts = new ArrayList<Broadcast>();

        NodeList broadcastNodes = doc.getElementsByTagName("broadcast");

        for (int i = 0; i < broadcastNodes.getLength(); i++) {

            Broadcast broadcast = new Broadcast();

            Element broadcastElement = (Element) broadcastNodes.item(i);

            Element element = null;

            // mmsUrl
            element = (Element) broadcastElement.getElementsByTagName("mmsUrl").item(0);
            broadcast.setMmsUrl(getCharacterDataFromElement(element));

            // title
            element = (Element) broadcastElement.getElementsByTagName("title").item(0);
            broadcast.setTitle(getCharacterDataFromElement(element));

            // add to list
            broadcasts.add(broadcast);

        }

    }

    private String getCharacterDataFromElement(Element e) {
        Node child = e.getFirstChild();
        if (child instanceof CharacterData) {
            CharacterData cd = (CharacterData) child;
            return cd.getData().trim();
        }
        return "";
    }

    public List<Broadcast> getBroadcasts() {
        return broadcasts;
    }

    public void setBroadcasts(List<Broadcast> broadcasts) {
        this.broadcasts = broadcasts;
    }
}
